package com.hnzq.cloud.driversend.listener;

import cn.hutool.core.lang.Snowflake;
import com.hnzq.cloud.IO.AddDriverworkIO;
import com.hnzq.cloud.IO.AddSendOrderIO;
import com.hnzq.cloud.IO.EditSendOrderIO;
import com.hnzq.cloud.IO.entity.FreDriverwork;
import com.hnzq.cloud.IO.entity.FreSend;
import com.hnzq.cloud.api.FreDriverworkApi;
import com.hnzq.cloud.api.FreSendOrderApi;
import com.hnzq.cloud.api.SiteQueryApi;
import com.hnzq.cloud.driversend.exception.OrderSendException;
import com.hnzq.cloud.driversend.exception.SendException;
import com.hnzq.cloud.driversend.param.SendToDriverParam;
import com.hnzq.cloud.dto.OneSiteDto;
import com.hnzq.cloud.dto.OrderDto;
import com.hnzq.cloud.model.Result;
import com.hnzq.cloud.util.ComUtil;
import com.hnzq.cloud.util.FreException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.RedissonBucket;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@Component
@RocketMQMessageListener(topic = "pay_Success",consumerGroup = "${rocketmq.consumer.group}",messageModel = MessageModel.BROADCASTING)
@Slf4j
public class OrderListener implements RocketMQListener<OrderDto> {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private SiteQueryApi siteQueryApi;
    @Autowired
    private FreSendOrderApi freSendOrderApi;
    @Autowired
    private FreDriverworkApi freDriverworkApi;
    @SneakyThrows
    @Override
    public void onMessage(OrderDto message) {
        Integer siteId = message.getSiteId();
        Result<OneSiteDto> site = siteQueryApi.findSite(siteId);
        OneSiteDto data = site.getData();
        Integer areaId = data.getAreaId();
        RBucket<Object> bucket = redissonClient.getBucket("send:area:" + areaId);

        AddSendOrderIO addSendOrderIO = new AddSendOrderIO();

        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(message.getOrderId());
        addSendOrderIO.setOrderIds(ids);
        addSendOrderIO.setSendWeight(new BigDecimal(1));
        addSendOrderIO.setAreaId(areaId);
        addSendOrderIO.setWarehouseId(1);
        addSendOrderIO.setSendPrice(new BigDecimal(5));
        System.out.println(bucket.get());
        if (!bucket.isExists()){
            System.out.println("进入redis不存在的情况");
            String endDate = ComUtil.nowDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date sDate = sdf.parse(endDate);
            System.out.println("String类型转Date类型 "+sDate);//要实现日期+1 需要String转成Date类型
            Format f = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(sDate);
            c.add(Calendar.DAY_OF_MONTH, 1);//利用Calendar 实现 Date日期+1天

            sDate = c.getTime();
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            endDate = sdf1.format(sDate);
            addSendOrderIO.setPlanFinishTime(endDate);
            System.out.println(addSendOrderIO.toString());
            addSendOrderIO.setDriverId(1);
            Result<Long> longResult = freSendOrderApi.addSendOrder(addSendOrderIO);
            System.out.println("long:"+longResult.getData());
            if (driverGet(longResult.getData()).getCode()!=200) {
                throw new OrderSendException("没有司机可以接单",500);
            }
            System.out.println(longResult.getCode());
            bucket.set(longResult.getData(),12, TimeUnit.HOURS);

        } else {
            System.out.println("进入redis存在配送单的情况");
            Long bucket1 = (Long) bucket.get();
            addSendOrderIO.setSendId(bucket1);
            Result result = freSendOrderApi.addToSend(addSendOrderIO);
            if (result.getCode()!=200){
                throw new OrderSendException("订单分配失败",500);
            }
        }


        log.info("收到消息：{}",message);
    }


    public Result driverGet(Long sendId) throws FreException {
        System.out.println("driverget"+sendId);
        Result<FreSend> byId = freSendOrderApi.getById(sendId);
        if (byId.getCode()!=200){
            throw new OrderSendException(byId.getMessage(),500);
        }
        System.out.println(byId.getData());
//        Result<List<Integer>> orders = freSendOrderApi.getOrders(sendToDriverParam.getSendId());
//        UpdateOrderListStatusParam updateOrderListStatusParam = new UpdateOrderListStatusParam();
//        updateOrderListStatusParam.setOrderIds(orders.getData());
//        updateOrderListStatusParam.setOrderStatus(2);
//        orderAPI.updateOrderListStatus(updateOrderListStatusParam);
        EditSendOrderIO editSendOrderIO = ComUtil.copyProperties(byId.getData(),EditSendOrderIO.class);
        Integer id = byId.getData().getAreaId();
        System.out.println(id);
        Result<FreDriverwork> byArea = freDriverworkApi.getByArea(id);
        System.out.println(1111);

        if (byArea.getCode()!=200||byArea.getData().getDriverStatus()!=0){
            throw new OrderSendException("不能分配该订单给这个司机",500);
        }
        editSendOrderIO.setDriverId(byArea.getData().getDriverId());
        System.out.println(editSendOrderIO);
        if (freSendOrderApi.editSendOrder(editSendOrderIO).getCode()!=200) {
            throw new OrderSendException("订单分配失败",500);
        }

        AddDriverworkIO build1 = AddDriverworkIO.builder().driverId(byArea.getData().getDriverId()).driverStatus(0).build();
        if (freDriverworkApi.editDriverworkStatus(build1).getCode()!=200) {
            throw new OrderSendException("司机分配失败，请稍后重试",500);

        }

        return Result.newInstance().setMessage("分配成功").setCode(200);
    }

}
